package com.yjt.common.utils;

import org.springframework.beans.BeanUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author 曾智平
 * @ClassName: CopyObject
 * @Description: 拷贝对象
 * @date 2021/6/16 14:54
 */
public class CopyObject {


    /**
     * 通用复制集合
     *
     * @param list
     * @param clazz
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> List<T> copyList(List<?> list, Class<T> clazz) throws Exception {
        List<T> tList = new ArrayList<>();
        if (list == null || list.isEmpty()) {
            return tList;
        }
        for (Object obj : list) {
            T t = clazz.newInstance();
            BeanUtils.copyProperties(obj, t);
            tList.add(t);
        }
        return tList;
    }

    /**
     * 深度拷贝集合
     *
     * @param list
     * @return
     */
    public static <T> List<T> deepCopyList(List<T> list) {
        try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
             ObjectOutputStream outputStream = new ObjectOutputStream(byteOut);
        ) {
            outputStream.writeObject(list);
            try (ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
                 ObjectInputStream inputStream = new ObjectInputStream(byteIn);
            ) {
                return (List<T>) inputStream.readObject();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Collections.emptyList();
    }

}
